package com.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.ITemplate;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/10.
 */
public class GeTuiUtil {
//    //采用"Java SDK 快速入门"， "第二步 获取访问凭证 "中获得的应用配置，用户可以自行替换
//    private static String getui_appId = "getui_appKey";
//    private static String getui_appKey = "ywqPdJgdHI7cMgkAcN6v56";
//    private static String getui_masterSecret = "uVmosRTXf87VB0tK7LS0P";

//    private static String getui_appId = "ZwDPOQNG0e9YVhKYVU3iL9";
//    private static String getui_appKey = "fqiNGhg7lt8dcpW4IoUw46";
//    private static String getui_masterSecret = "DFFzK3Btds73FRFhpanYoA";

    private static String getui_appId = "xks1UMPGRb81QGaajBpLL8";
    private static String getui_appKey = "ty9yErS5OX8G1dWeUbLHi2";
    private static String getui_masterSecret = "MwIgse28PT7T4lUQvkXl36";

    //别名推送方式
    // static String Alias = "";
    static String host = "http://sdk.open.api.igexin.com/apiex.htm";

    /**
     * 推送信息（因为需要自定义通知栏，只需要传 透传内容）
     *
     * @param CID     客户端id
     * @param text    苹果apn通道的
     * @param content 透传内容
     * @return
     */
    public boolean pushMessage(String CID, String text, String content, String autoBadge) {
        IGtPush push = new IGtPush(host, getui_appKey, getui_masterSecret);
        ITemplate template = transmissionTemplate(text, content, autoBadge);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(getui_appId);
        target.setClientId(CID);
        //target.setAlias(Alias);
        IPushResult ret;
        try {
            ret = push.pushMessageToSingle(message, target);
            System.out.println(ret.getResponse());
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            if ("ok".equals(ret.getResponse().get("result"))) {
                return true;
            }
        } else {
        }
        return false;
    }


    /**
     * 安卓推送消息模板
     *
     * @param title
     * @param text
     * @param content
     * @return
     */
    private NotificationTemplate notificationTemplate(String title, String text, String content) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(getui_appId);
        template.setAppkey(getui_appKey);
        // 设置通知栏标题与内容
        template.setTitle(title);
        template.setText(text);
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(content);
        return template;
    }


    /**
     * IOS推送消息模板
     *
     * @param content
     * @return
     */
    private TransmissionTemplate transmissionTemplate(String text, String content, String autoBadge) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(getui_appId);
        template.setAppkey(getui_appKey);
        template.setTransmissionContent(content);//透传内容
        template.setTransmissionType(2);
        APNPayload payload = new APNPayload();
        payload.addCustomMsg("content", content);
        payload.setContentAvailable(1);
        payload.setAutoBadge(autoBadge);
        payload.setSound("default");
        payload.setCategory("$由客户端定义");
        //简单模式APNPayload.SimpleMsg
        payload.setAlertMsg(new APNPayload.SimpleAlertMsg(text));//走苹果的APN通道
        //字典模式使用下者
        //payload.setAlertMsg(getDictionaryAlertMsg());
        template.setAPNInfo(payload);
        return template;
    }

    private APNPayload.DictionaryAlertMsg getDictionaryAlertMsg() {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody("body");
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image");
        // IOS8.2以上版本支持
        alertMsg.setTitle("Title");
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }

    /**
     * 组装消息
     *
     * @param title       标题
     * @param message     消息内容
     * @param badgeNumber 未读消息条数
     * @param messageId   消息id
     * @param type        //消息类型
     * @param style       //样式编号
     * @param smallIcon   //小图标
     * @param bigIcon     //大图标
     * @return
     */
    private String messageToJson(String loginId, String title, String message, Integer badgeNumber, Integer wayBillCount, Integer walletCount, Integer messageId, String type, Integer style, String smallIcon, String bigIcon) {
        Map<String, Object> icon = new HashMap();
        icon.put("smallIcon", smallIcon);//小图标
        icon.put("bigIcon", bigIcon);//大图标

        Map<String, Object> content = new HashMap();
        content.put("title", title);// string消息标题
        content.put("message", message);// string消息内容
        content.put("badgeNumber", badgeNumber);//未读消息条数
        content.put("wayBillCount", wayBillCount);//运单未读消息条数
        content.put("walletCount", walletCount);//钱包未读消息条数
        content.put("icon", icon);//图标

        Map<String, Object> transmissionContent = new HashMap();//穿透消息
        transmissionContent.put("id", messageId);//消息id
        transmissionContent.put("userId", loginId);//消息id
        transmissionContent.put("type", type);//消息类型
        transmissionContent.put("style", style);//样式编号
        transmissionContent.put("content", content);//消息
        return JSON.toJSONString(transmissionContent);
    }

    /**
     * 推送透传
     *
     * @param content
     * @return
     */
    public boolean pushTransmission(String CID, String content) {
        IGtPush push = new IGtPush(host, getui_appKey, getui_masterSecret);
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(getui_appId);
        template.setAppkey(getui_appKey);
        template.setTransmissionContent(content);//透传内容
        template.setTransmissionType(2);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        Target target = new Target();
        target.setAppId(getui_appId);
        target.setClientId(CID);
        //target.setAlias(Alias);
        IPushResult ret;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        System.out.println(ret.getResponse());
        if (ret != null) {
            if ("ok".equals(ret.getResponse().get("result"))) {
                return true;
            }
        } else {
        }
        return false;

    }

    public static boolean allPushTransmission(String content) {
        IGtPush push = new IGtPush(host, getui_appKey, getui_masterSecret);
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(getui_appId);
        template.setAppkey(getui_appKey);
        template.setTransmissionContent(content);//透传内容
        template.setTransmissionType(2);
        AppMessage message = new AppMessage();
        message.setData(template);
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(getui_appId);
        message.setAppIdList(appIdList);
        message.setConditions(cdt);
        IPushResult ret = push.pushMessageToApp(message, "有新的通知信息");
        System.out.println(ret.getResponse().toString());//TODO  换成logger日志、
        if (ret != null) {
            if ("ok".equals(ret.getResponse().get("result"))) {
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) throws Exception {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","");
        allPushTransmission(jsonObject.toJSONString());
    }


    @Test
    public void test() throws InterruptedException {
//        String mess = messageToJson("APP20170104092849aGzOj", "恭喜您获取我公司提供的iphone山寨一台", "请先支付100元运费", 12, 1, 1, 1, "Y", 0, "", "");
//        System.out.println(mess);
//
//       // String ms="{\"style\":0,\"id\":365,\"type\":\"A\",\"userId\":\"APP20161224115858jizrI\",\"content\":{\"icon\":{\"bigIcon\":\"\",\"smallIcon\":\"\"},\"walletCount\":0,\"badgeNumber\":1,\"wayBillCount\":1,\"title\":\"路畅消息\",\"message\":\"您在鹏达物流公司承运的日照-防城港的货，现在可以预提运费了\"}}";
//      //0fcd3b54d9846024e44d336cb3d8eb45
//      //  1e348ada77c15adcc5d6c8dcf1137a74
//       // boolean bool = pushMessage("1e348ada77c15adcc5d6c8dcf1137a74", "测试推送内容", mess);
//       boolean bool1 = pushMessage("3825b8f73a82aeb0c793a082181437ed", "这是来自iPhone测试推送内容", mess,"3");
//
//
//        //3825b8f73a82aeb0c793a082181437ed
//       // System.out.println(bool);
//        System.out.println(bool1);
        JSONObject json = new JSONObject();
        JSONObject json1 = new JSONObject();
        json1.put("demandId", "1111");
        json.put("content", json1);
        json.put("type", "grabSingle");
        System.out.println(json.toJSONString());
        pushTransmission("", json.toJSONString());

    }
}
